package com.zhj.pay.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

public class CircleView extends View{
    Paint mBackPaint;
    Paint mForegroundPaint;
    Paint mTextPaint;


    RectF mRect;

    int mX;
    int mY;
    int mRadius = 200;
    int mStrokeWidth = 40;
    int mStrokeWidthHalf = mStrokeWidth / 2;

    int mProgress = 0;
    int mTargetProgress = 40;
    int mMaxProgress = 100;


    public CircleView(Context context) {
        this(context,null);
    }

    public CircleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mBackPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mForegroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

        mBackPaint.setStyle(Paint.Style.STROKE);
        mBackPaint.setColor(Color.WHITE);
        mBackPaint.setStrokeWidth(mStrokeWidth);

        mForegroundPaint.setColor(Color.GREEN);
        mForegroundPaint.setStyle(Paint.Style.STROKE);
        mForegroundPaint.setStrokeWidth(mStrokeWidth);

        mTextPaint.setColor(Color.BLUE);
        mTextPaint.setTextSize(40);
        mTextPaint.setTextAlign(Paint.Align.CENTER);


        mX = mRadius + mStrokeWidthHalf;
        mY = mRadius + mStrokeWidthHalf;

        mRect = new RectF();
        mRect.left = mStrokeWidthHalf;
        mRect.top = mStrokeWidthHalf;
        mRect.right = mRadius * 2 + mStrokeWidthHalf;
        mRect.bottom = mRadius * 2 + mStrokeWidthHalf;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        float angle = mProgress /(float) mMaxProgress  * 360;

        canvas.drawCircle(mX,mY,mRadius,mBackPaint);
        canvas.drawArc(mRect,-90,angle,false,mForegroundPaint);

        String progress = mProgress + "%";
        canvas.drawText(progress,mX,mY,mTextPaint);

        if(mProgress < mTargetProgress){
            mProgress += 2;
        }

        invalidate();
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = getRealSize(widthMeasureSpec);
        int height = getRealSize(heightMeasureSpec);

        setMeasuredDimension(width,height);
    }

    private int getRealSize(int measereSpce){
        int result = -1;

        int mode = MeasureSpec.getMode(measereSpce);
        int size = MeasureSpec.getSize(measereSpce);

        if(mode == MeasureSpec.AT_MOST || mode == MeasureSpec.UNSPECIFIED){
            result = mRadius * 2 + mStrokeWidth;//注意这块
        }else {
            result = size;
        }

        return result;
    }

}
